package com.jinit.jia.boot.autoconfigure.web.servlet;

import com.jinit.jia.boot.web.embedded.tomcat.TomcatWebServer;
import com.jinit.jia.boot.web.server.WebServer;
import org.apache.catalina.startup.Tomcat;

import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;

/**
 * TomcatServletWebServerFactory
 *
 * @author JInit
 * @date 2021-08-06
 */
public class TomcatServletWebServerFactory {
    /**
     * 基础目录
     */
    private File baseDirectory;

    /**
     * 监听端口：默认8080
     */
    private int port = 8080;

    /**
     * 获取web服务
     * @return
     */
    public WebServer getWebServer() {
        // 实例化一个Tomcat
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(this.port);
        File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
        // 设置Tomcat的工作临时目录
        try {
            tomcat.addWebapp("/",baseDir.getAbsolutePath());
        } catch (ServletException e) {
            e.printStackTrace();
        }
        return getTomcatWebServer(tomcat);
    }

    /**
     * 获取tomcat服务
     * @param tomcat
     * @return
     */
    protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
        return new TomcatWebServer(tomcat, getPort() >= 0);
    }

    /**
     * 创建临时目录
     * @param prefix 指定前缀
     * @return
     */
    protected final File createTempDir(String prefix) {
        try {
            File tempDir = File.createTempFile(prefix + ".", "." + getPort());
            tempDir.delete();
            tempDir.mkdir();
            tempDir.deleteOnExit();
            return tempDir;
        }
        catch (IOException ex) {
            throw new RuntimeException("创建临时目录异常", ex);
        }
    }

    /**
     * 获取监听端口
     * @return
     */
    public int getPort() {
        return this.port;
    }
}
